﻿using Manon.ConfigCenter.Output;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;

namespace Manon.ConfigCenter
{
    public static class ConfigCenterServiceCollectionExtensions
    {
        public static T UseConfigCenter<T>(this IServiceCollection services) where T : ConfigCenterBaseOutput, new()
        {
            IHostingEnvironment env = services.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
            var model = ConfigCenterHelper.loadSettings<T>();
            env.EnvironmentName = model.AspnetCoreEnvironment ?? AspnetCoreEnvironmentConst.Development;

            services.Configure<T>(options =>
            {
                PropertyInfo[] propertys = options.GetType().GetProperties();
                PropertyInfo[] settingpropertys = model.GetType().GetProperties();
                foreach (PropertyInfo property in propertys)
                {
                    foreach (PropertyInfo settingproperty in settingpropertys)
                    {
                        if (property.Name == settingproperty.Name)
                        {
                            property.SetValue(options, settingproperty.GetValue(model), null);
                        }
                    }
                }
            });
            return model;
        }
    }
}
